package com.caigou.controller.front;

import com.caigou.util.Result;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/wechat")
public class WeChatSharingController {
    @Resource
    private WxMpService wxMpService;

    /**
     * 微信回调处理
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/callback")
    public String callback(@RequestParam("signature") String signature, @RequestParam("nonce") String nonce, @RequestParam("timestamp") String timestamp,
                           HttpServletRequest request) throws Exception{
        String echostr = "";
        System.out.println("signature：" + signature);
        System.out.println("nonce：" + nonce);
        System.out.println("timestamp：" + timestamp);
        // 验证消息签名，说明不是公众平台发送来的消息
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            return "非法访问";
        }
        // 说明是一个仅仅用来验证的请求，回显echostr
        echostr = request.getParameter("echostr");
        if (!StringUtils.isEmpty(echostr)) {
            return echostr;
        }
        String encryptType = StringUtils.isEmpty(request.getParameter("encrypt_type")) ? "raw" : request.getParameter("encrypt_type");
        if ("raw".equals(encryptType)) {
            // 明文传输的消息
            WxMpXmlMessage message = WxMpXmlMessage.fromXml(request.getInputStream());
            return message.toString();
        }
        if ("aes".equals(encryptType)) {
            // 是aes加密的消息
            String msgSignature = request.getParameter("msg_signature");
            WxMpXmlMessage message = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), wxMpService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
            return message.toString();
        }
        return "不可识别的加密类型";
    }

    @RequestMapping(value = "/share")
    public Result share(@RequestParam("url") String url){
        try {
            WxJsapiSignature signature = wxMpService.createJsapiSignature(url);
            return Result.success(signature);
        } catch (WxErrorException e) {
            log.error("分享出现异常");
            log.error(e.getMessage());
            return Result.error("分享出现异常");
        }
    }
}
